#include <Line>
#include <Polygon>
#include <Core>
#include <Document>
#include <QtOpenGL>
#include <ControlPointHelper>

Line::Line(QObject *parent) :
    Poly(parent)
{
}

void Line::draw() const
{
    boost::shared_ptr<Renderer> renderer = Core::instance().renderer();
    renderer->drawLine(m_start, m_end, Qt::white);

    QPointer<Document> doc = qobject_cast<Document*>(parent());
    Q_ASSERT(doc);

    float oneOverZoom = 1.0f/doc->zoom();

    QRectF cp1(m_start.x() - 3*oneOverZoom, m_start.y() - 3*oneOverZoom, 6*oneOverZoom, 6*oneOverZoom);
    QRectF cp2(m_end.x() - 3*oneOverZoom, m_end.y() - 3*oneOverZoom, 6*oneOverZoom, 6*oneOverZoom);
    QRectF cp3(pos().x() - 3*oneOverZoom, pos().y() - 3*oneOverZoom, 6*oneOverZoom, 6*oneOverZoom);

    renderer->drawRect(cp1, QColor::fromRgb(255, 255, 0));
    renderer->drawRect(cp2, QColor::fromRgb(255, 255, 0));
    renderer->drawRect(cp3, QColor::fromRgb(255, 0, 0));
}

QPointer<Poly> Line::toPoly() const
{
    return 0;
}

void Line::setStart(const QPointF &start)
{
    if(m_start == start) return;
    m_start = start;
    updateTransform();

    emit elementChanged();
}

void Line::setEnd(const QPointF &end)
{
    if(m_end == end) return;
    m_end = end;
    updateTransform();

    emit elementChanged();
}

QPointF Line::start() const
{
    return m_start;
}

QPointF Line::end() const
{
    return m_end;
}

float Line::length() const
{
    QPointF v = m_end - m_start;
    float l = sqrt(v.x()*v.x() + v.y()*v.y());
    return l;
}

QPointF Line::unitVector() const
{
    QPointF vec = m_end - m_start;
    QPointF unitVec = vec/length();
    return unitVec;
}

void Line::updateTransform()
{
    QPointF center = (m_start + m_end)/2.0f;
    setPos(center);
}
